package control;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.bean.aluguel;
import model.bean.livro;
import model.bean.usuario;
import model.dao.AluguelDao;
import model.dao.LivroDao;

/**
 * Servlet implementation class ServletUsuario
 */
@WebServlet("/ConsultaLivroManager")
public class ServletConsultaLivroManager extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ServletConsultaLivroManager() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String acao = request.getParameter("acao");
		String id = request.getParameter("id");
		String nome = request.getParameter("nome");

		if (acao.equals("0")) {
			response.sendRedirect("IndexManager.jsp?content=11&filtro=" + nome);
		} else {
			aluguel obj = new aluguel();
			livro livro = new livro();
			usuario usuario = new usuario();
			usuario.setId(Integer.parseInt(request.getParameter("usuario")));

			livro.setId(Integer.parseInt(id));
			obj.setUsuario(usuario);
			obj.setDataAluguel(new Date());
			obj.setLivro(livro);
			AluguelDao dao = new AluguelDao();
			dao.create(obj);
			LivroDao daoL = new LivroDao();
			daoL.qtdMenos(Integer.parseInt(id));

			String urlRetorno = request.getHeader("referer");
			urlRetorno = urlRetorno.replace("?", ";");
			String[] urls = urlRetorno.contains(";") ? urlRetorno.split(";")
					: null;
			if (urls != null && urls.length > 0) {
				response.sendRedirect(urls[0] + "?content=11");
			} else {
				response.sendRedirect(urlRetorno + "?content=11");
			}
		}
	}
}
